<template>
  <basePage ref="basePage">
    <view class="order-payment-con">
      <view class="list-bg list-group-row">
        <view class="list-title">
          配送方式
          <view class="number">{{ curOrderDetailData.sentTypeName }}</view>
        </view>
      </view>
      <AddressBar :order-detail-data="curOrderDetailData" />
      <OrderProductList
        :order-detail-data="curOrderDetailData"
        :order-items-detail-data="curOrderProductList"
        :show-warehouse-label="showWarehouseLabel"
        :all-goods-page-path="'/goodsPages/orderAllgoods'"
        :total-record="totalRecord"
        :page-type="'pay'"
      />
      <view class="list-bg list-group-row">
        <view class="list-title">
          订单号
          <view class="number">
            {{ curOrderDetailData.orderNo }}
            <button
              class="btn-border"
              :type="'default'"
              plain="true"
              @click="copyFn(curOrderDetailData.orderNo)"
            >
              复制
            </button></view>
        </view>
        <view class="list-title">
          收款方式
          <view class="number">现款</view>
        </view>
      </view>
      <view v-if="curOrderDetailData.customerReceiverTypeId!=0" class="tel-sale-bottom">
        <button
          :type="'default'"
          class="tel-sale-btn"
          :plain="true"
          @click="callPhoneFn"
        >
          <icon class="tel-icon" />
          {{ curOrderDetailData.customerReceiverTypeId == 1 ? '联系销售' : '联系客服' }}
        </button>
      </view>
      <view class="sticky-bottom">合计：<text class="price">¥ {{ curOrderDetailData.showProductPrice && curOrderDetailData.showProductPrice == 1 ? curOrderDetailData.billAmount : '*.*' }}</text>
        <button
          v-if="(curOrderDetailData.orderStatus == 0 || curOrderDetailData.orderStatus == 10) && curOrderDetailData.settleType==1001 && (curOrderDetailData.billDate == curDate || curOrderDetailData.billDate == setFormatDate(curDate))"
          class="sticky-btn btn-orange"
          :class="isClickPayBtn ? 'disabled-btn' : ''"
          :disabled="isClickPayBtn"
          :type="'default'"
          :plain="true"
          @click="$u.throttle(requestSubscribeMessage, 4000)"
        >
          去支付
        </button>
      </view>
      <!-- 登录弹框 -->
      <u-popup :show="showPopVisible" :round="5" mode="bottom" height="420" @close="closePop">
        <RegisterPop
          :page-type="'pay'"
          :branch-data="curBranchData"
          @paymentFn="requestSubscribeMessage"
          @closePopFn="closePop"
        />
      </u-popup>
    </view>
  </basePage>
</template>

<script>
import basePage from '@/components/base-page';
import RegisterPop from '@/components/register-pop';
import OrderProductList from '@/components/order-product-list/order-product-list'
import AddressBar from '@/components/addressBar/address-bar'
import { loginMixin } from '@/login/loginMixin'
import {
  // lockOrderFn,
  getSystemTime,
  formatDate,
  checkMemeberStatusFn,
} from '@/common/common'
import {
  prePayMethod,
  payMethod
} from '@/payments/payMethod'
export default {
  name: 'Index',
  components: {
    OrderProductList,
    AddressBar,
    RegisterPop,
    basePage
  },
  mixins: [loginMixin],
  props: {
    orderDetailData: {
      type: Object,
      default: null
    },
    orderProductList: {
      type: Array,
      default: null
    },
    showWarehouseLabel: {
      type: Boolean,
      default: false
    },
    totalRecord: {
      type: Number,
      default: 0
    },
  },
  data() {
    return {
      showPopVisible: false,
      orderNo: '',
      curDate: '',
      prePayInfo: {}, // prePay预支付接口返回参数信息
      isClickPayBtn: false, // 防止重复点击支付按钮重复支付，4秒后重置状态
    }
  },
  computed: {
    curOrderDetailData() {
      return this.orderDetailData
    },
    curOrderProductList() {
      return this.orderProductList
    },
    curBranchData() {
      const branchData = {
        branchId: this.curOrderDetailData.branchId,
        branchName: this.curOrderDetailData.branchName,
        settleType: this.curOrderDetailData.settleType,
      }
      return branchData
    }
  },
  onLoad(option) {
  },
  mounted() {
    this.getAccountTimeFn()
  },
  methods: {
    prePayMethod,
    payMethod,
    /*未登录跳转登录*/
    returnLoginFn() {
      const callbackUrl = `/payments/payment/payment`
      const urlParams = JSON.stringify({ orderNo: this.curOrderDetailData.orderNo, pageSource: 'local' })
      uni.redirectTo({
        url: `/login/login/codeLogin?type=payPage&callbackUrl=${callbackUrl}&urlParams=${urlParams}&registParams=${JSON.stringify(this.curBranchData)}`
      })
    },
    /*获取时间*/
    async getAccountTimeFn() {
      const time = await getSystemTime()
      this.curDate = formatDate(new Date(time), 'yyyy-mm-dd')
    },
    setFormatDate(time) {
      const orderNextTime = formatDate(new Date(new Date(time).getTime() + (24 * 60 * 60 * 1000)), 'yyyy-mm-dd')
      return orderNextTime
    },
    copyFn(val) {
      uni.setClipboardData({
        data: val,
        success: function(res) {
          uni.getClipboardData({
            success: function(res) {
              uni.showToast({
                title: '已复制到剪贴板'
              });
            }
          });
        }
      })
    },
    async prePayFn() {
      const {
        orderNo: orderPayNo,
        customerCode,
        branchId: belongGroupId,
        sendDepartmentId,
        billAmount: totalOrderAmount
      } = this.curOrderDetailData
      const prePayParams = { platform: 'MD', orderId: orderPayNo, totalAmount: totalOrderAmount, customerCode, sendDepartmentId, belongGroupId }
      this.prePayInfo = await this.prePayMethod(prePayParams).catch((e) => {
        this.$u.toast(e.message)
      })
    },
    /*通知消息授权*/
    async requestSubscribeMessage() {
      if (this.isClickPayBtn) {
        return
      }
      this.isClickPayBtn = true
      setTimeout(() => {
        this.isClickPayBtn = false
      }, 4000)
      if (!(this.vuex_loginStatus && this.vuex_accountInfo && this.vuex_accountInfo.loginAccount)) { // 未登录状态登录
        this.loginEvent(this.curBranchData, 'pay')
        return
      }
      // 判断当前账号是否是有效账号
      const memeberStatus = await checkMemeberStatusFn({ loginAccount: this.vuex_accountInfo.loginAccount })
      if (!memeberStatus) {
        this.returnLoginFn()
        return
      }
      // 订单支付锁定状态为”否(0)“时，点击【订单确认】/【去支付】时，提醒”您的订单客服正在修改中，请稍后再试“
      if (this.curOrderDetailData.lockedStatus == 0) {
        this.$u.toast('您的订单客服正在修改中，请稍后再试')
        return
      }
      /*const phoneNum = this.vuex_accountInfo.mobilePhone
      // #ifdef MP-ALIPAY
      if (!this.vuex_accountInfo.userId) {
        this.$u.toast('请使用手机号' + phoneNum.replace(phoneNum.substring(3, 7), '****') + '的手机号，支付宝一键登录后进行支付')
        return
      }
      // #endif
      // #ifdef MP-WEIXIN
      if (!this.vuex_accountInfo.openid) {
        this.$u.toast('请使用手机号' + phoneNum.replace(phoneNum.substring(3, 7), '****') + '的手机号，微信一键登录后进行支付')
        return
      }*/
      // #endif
      /*支付成功通知模板id：7f9bdd45cf354d38998baeabcdc164b0
            拣货成功通知模板id：89ecaf7f49fd4b37a72beff65d7e64c8
            19654,"店面自提"、19651,"无货自提"、19655,"配送客户自提"*/
      let entityIds = []
      if (this.curOrderDetailData.orderType == 19654 || this.curOrderDetailData.orderType == 19651 || this.curOrderDetailData.orderType == 19655) {
        entityIds = ['7f9bdd45cf354d38998baeabcdc164b0', '89ecaf7f49fd4b37a72beff65d7e64c8']
      } else {
        entityIds = ['7f9bdd45cf354d38998baeabcdc164b0']
      }
      // #ifdef MP-ALIPAY
      my.requestSubscribeMessage({
        entityIds: entityIds,
        success: (res) => {
          // this.$u.toast('接口调用成功的回调')
          this.paymentFn();
        },
        fail: (res) => {
          this.paymentFn();
        },
        complete: (res) => {
          // this.paymentFn();
        }
      });
      // #endif
      // #ifdef MP-WEIXIN
      this.paymentFn()
      // #endif
    },
    /*去支付，获取支付信息*/
    async paymentFn() {
      await this.prePayFn()
      if (!this.prePayInfo) {
        return
      }
      let payWayUnifyCode = 'WechatPay' // 支付方式统一编码，用于不区分支付渠道，由服务端根据规则选择支付渠道 WechatPay=微信支付 AliPay=支付宝 EPay=网银支付 QuickPay=快捷 AccountPay=账期 PingAnPay=平安支付
      // #ifdef MP-ALIPAY
      payWayUnifyCode = 'AliPay'
      // #endif
      const {
        orderNo,
        billAmount
      } = this.curOrderDetailData
      const {
        needPayAmount,
        payId,
        totalAmount,
      } = this.prePayInfo
      const payParams = {
        platform: 'MD',
        payWayUnifyCode,
        payId,
        payableAmount: needPayAmount,
        payInfoTotalAmount: totalAmount
      }
      // 支付成功回调函数
      const successFn = ({ paySerialnoId }) => {
        uni.redirectTo({
          url: `/payments/paymentSuccess/index?id=${paySerialnoId}&amount=${billAmount}&orderno=${orderNo}`
        });
        this.$u.vuex('vuex_qrOrderNo', '')
      }
      // 支付失败回调函数
      const failFn = () => {
        this.$u.toast('支付失败')
      }
      await this.payMethod(payParams, successFn, failFn)
    },
    /*联系销售*/
    callPhoneFn() {
      let phoneNumber = ''
      if (this.curOrderDetailData.customerReceiverTypeId == 1) {
        phoneNumber = this.curOrderDetailData.departmentPhone
      } else if (this.curOrderDetailData.customerReceiverTypeId == 2) {
        phoneNumber = this.curOrderDetailData.rolePhone
      }
      uni.makePhoneCall({
        phoneNumber: phoneNumber,
        fail: (res) => {
          this.$u.toast('拨打失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.order-payment-con{
  padding-top:10rpx;
  padding-bottom:170rpx;
  .tel-sale-bottom {
    position: fixed;
    bottom:170rpx;
    height: 68rpx;
    width: 100%;
    .tel-sale-btn{
      width:710rpx;
      height:68rpx;
      margin: 0 auto;
      line-height: 68rpx;
      border-radius:8px;
      border: 0!important;
      font-size: 28rpx;
      color:#fff!important;
      background: #474747;
    }
    .tel-icon{
      background:url("../../static/image/tel-sale.png") no-repeat 0 0/100%;
      width: 24rpx;
      height: 26rpx;
      position: relative;
      margin-right:6rpx;
      top:2rpx;
    }
  }
  .btn-border{
    display: inline;
    height: 36rpx;
    line-height: 34rpx;
    color: #333;
    border: 2rpx solid #ddd;
    padding:0 20rpx!important;
    font-size: $uni-font-size-sm;
    /*#ifdef MP-ALIPAY*/
    margin: -6rpx 0 0 10rpx;
    /*#endif*/
    /*#ifdef MP-WEIXIN*/
    margin: 10rpx 0 0 10rpx;
    /*#endif*/
    border-radius:4rpx;
  }
  .disabled-btn{
    background: $uni-text-color-disable;
  }
  .sticky-btn{
    float: right;
    margin:8rpx 0 0 58rpx;
  }
}
</style>
